package com.javaee.lucene;

import java.io.StringReader;
import java.nio.file.Paths;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.document.Field;
import com.javaee.entity.Test;
import com.javaee.util.DateUtil;
import com.javaee.util.StringUtil;

public class LuceneTest {

   private Directory dir=null;

	/**
	 * 获取IndexWriter实例
	 * @return
	 * @throws Exception
	 */
	private IndexWriter getWriter()throws Exception{
		dir=FSDirectory.open(Paths.get("D://lucene"));
//		dir=FSDirectory.open(Paths.get("/home/tomcat/lucene"));
		SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
		IndexWriterConfig iwc=new IndexWriterConfig(analyzer);
		IndexWriter writer=new IndexWriter(dir, iwc);
		return writer;
	}
	
	/**
	 * 添加索引
	 * @param test
	 */
	public void addIndex(Test test)throws Exception{
		IndexWriter writer=getWriter();
		Document doc=new Document();
		doc.add(new StringField("id",String.valueOf(test.getId()),Field.Store.YES));
		doc.add(new TextField("name",test.getName(),Field.Store.YES));
		doc.add(new TextField("age",test.getAge(),Field.Store.YES));
		doc.add(new TextField("gender",test.getGender(),Field.Store.YES));
		writer.addDocument(doc);
		writer.close();
	}
	
	/**
	 * 更新索引
	 * @param test
	 * @throws Exception
	 */
	public void updateIndex(Test test)throws Exception{
		IndexWriter writer=getWriter();
		Document doc=new Document();
		doc.add(new StringField("id",String.valueOf(test.getId()),Field.Store.YES));
		doc.add(new TextField("name",test.getName(),Field.Store.YES));
		doc.add(new TextField("age",test.getAge(),Field.Store.YES));
		doc.add(new TextField("gender",test.getGender(),Field.Store.YES));
		writer.updateDocument(new Term("id", String.valueOf(test.getId())), doc);
		writer.close();
	}
	
	/**
	 * 删除指定的索引
	 * @param blogId
	 * @throws Exception
	 */
	public void deleteIndex(String Id)throws Exception{
		IndexWriter writer=getWriter();
		writer.deleteDocuments(new Term("id",Id));
		writer.forceMergeDeletes(); // 强制删除
		writer.commit();
		writer.close();
	}
	
	/**
	 * 查询信息
	 * @param q 查询关键字
	 * @return
	 * @throws Exception
	 */
	public List<Test> searchBlog(String q)throws Exception{
		dir=FSDirectory.open(Paths.get("D://lucene"));
//		dir=FSDirectory.open(Paths.get("/home/tomcat/lucene"));
		IndexReader reader = DirectoryReader.open(dir);
		IndexSearcher is=new IndexSearcher(reader);
		BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder();
		SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
		QueryParser parser=new QueryParser("name",analyzer);
		Query query=parser.parse(q);
		booleanQuery.add(query,BooleanClause.Occur.SHOULD);
		TopDocs hits=is.search(booleanQuery.build(), 100);
		QueryScorer scorer=new QueryScorer(query);  
		Fragmenter fragmenter = new SimpleSpanFragmenter(scorer);  
		SimpleHTMLFormatter simpleHTMLFormatter=new SimpleHTMLFormatter("<b><font color='red'>","</font></b>");//标注关键字为红色
		Highlighter highlighter=new Highlighter(simpleHTMLFormatter, scorer);
		highlighter.setTextFragmenter(fragmenter);  
		List<Test> blogList=new LinkedList<Test>();
		for(ScoreDoc scoreDoc:hits.scoreDocs){
			Document doc=is.doc(scoreDoc.doc);
			Test test=new Test();
			test.setId(Integer.parseInt(doc.get(("id"))));
			test.setAge(doc.get(("age")));
			test.setGender(doc.get("gender"));
			String name=StringEscapeUtils.escapeHtml(doc.get("name"));
			if(name!=null){
				TokenStream tokenStream = analyzer.tokenStream("name", new StringReader(name));
				String hTitle=highlighter.getBestFragment(tokenStream, name);
				if(StringUtil.isEmpty(hTitle)){
					test.setName(name);
				}else{
					test.setName(hTitle);					
				}
			}
			
			blogList.add(test);
		}
		return blogList;
	}
}
